package executable.knapsack;

public class BruteForceKnapsack {

    private int maxPrice;
    private int maxAllowedWeight;
    private int[] prices;
    private int[] weight;
    private boolean[] actual;
    private boolean[] maxItems = new boolean[0];

    public BruteForceKnapsack(Item[] items, int maxAllowedWeight2) {
        maxAllowedWeight = maxAllowedWeight2;
        maxPrice = 0;
        prices = new int[items.length];
        weight = new int[items.length];
        actual = new boolean[items.length];
        for (int i = 0; i < items.length; i++) {
            prices[i] = items[i].getPrice();
            weight[i] = items[i].getWeight();
        }
    }

    public int compute() {
        compute(actual.length - 1, 0, 0);
        return maxPrice;
    }

    public void compute(int index, int priceInKnapsack, int weightInKnapsack) {
        if (index < 0) {
            checkAndSaveMax(priceInKnapsack);
            return;
        }
        actual[index] = true;
        int newWeight = weightInKnapsack + weight[index];
        if (newWeight <= maxAllowedWeight) {
            compute(index - 1, priceInKnapsack + prices[index], newWeight);
        } else {
            checkAndSaveMax(priceInKnapsack);
        }
        actual[index] = false;
        compute(index - 1, priceInKnapsack, weightInKnapsack);
    }

    protected void checkAndSaveMax(int priceInKnapsack) {
        if (priceInKnapsack > maxPrice) {
            maxPrice = priceInKnapsack;
//            maxItems = Arrays.copyOf(actual, actual.length);
        }
    }
}
